#include "qdynamicform.h"
#include "widgets/qinsertwidget.h"
#include "widgets/qmanagerwidget.h"
#include "widgets/qinsertwidget.h"
#include "widgets/qupdatewidget.h"
#include <QVector>
#include <QSqlQuery>
QT_BEGIN_NAMESPACE


class QDynamicFormPrivate
{
    Q_DECLARE_PUBLIC(QDynamicForm)
public:
    QDynamicFormPrivate(QDynamicForm *q);
    void showManageWidget();
    void showInsertWidget();
    void showUpdateWidget();

private:
    bool init();
    bool initCreateTable();
    QSqlDatabase *db;
    QTableAttribute *tableAttribute;
    QDynamicForm *q_ptr;
    QManagerWidget *managerWidget;
    QInsertWidget  *insertWidget;
    QUpdateWidget * updateWidget;
};

QDynamicFormPrivate::QDynamicFormPrivate(QDynamicForm *q)
    : q_ptr(q)
    , managerWidget( new QManagerWidget())
    , insertWidget(new QInsertWidget())
    , updateWidget(new QUpdateWidget())
{

}

bool QDynamicFormPrivate::init()
{
    managerWidget->init(db,tableAttribute);
    insertWidget->init(db,tableAttribute);
    updateWidget->init(db,tableAttribute);
    return initCreateTable();
}

bool QDynamicFormPrivate::initCreateTable()
{

    QString table_name = tableAttribute->tableName;
    QString create_table_sql = QString("CREATE TABLE IF NOT EXISTS %1 (").arg(table_name);
    for(int i = 0 ;i < tableAttribute->fieldAttributes.size() ;i++){
        auto item = tableAttribute->fieldAttributes.at(i);
        create_table_sql.append(item.createSql);
        if(i != tableAttribute->fieldAttributes.size() -1){
            create_table_sql.append(",");
        }
    }
    create_table_sql.append(");");
    QSqlQuery query(create_table_sql,*db);
    return query.exec();
}

void QDynamicFormPrivate::showManageWidget()
{
    managerWidget->showNormal() ;
}

void QDynamicFormPrivate::showInsertWidget()
{
    insertWidget->showNormal();
}

void QDynamicFormPrivate::showUpdateWidget()
{
    updateWidget->showNormal();
}

QDynamicForm::QDynamicForm()
    :d_ptr(new QDynamicFormPrivate(this))
{
    Q_D(QDynamicForm);
}

void QDynamicForm::showManagerWidget()
{
    Q_D(QDynamicForm);
    d->showManageWidget();
}

void QDynamicForm::showInsertWidget()
{
    Q_D(QDynamicForm);
    d->showInsertWidget();
}

void QDynamicForm::showUpdateWidget()
{
    Q_D(QDynamicForm);
    d->showUpdateWidget();

}

bool QDynamicForm::init(QSqlDatabase *_db, QTableAttribute *_tableAttribute)
{
    Q_D(QDynamicForm);
    if(_db == nullptr || _tableAttribute == nullptr){
        return false;
    }
    d->db = _db;
    d->tableAttribute = _tableAttribute;
    return d->init();

}
QT_END_NAMESPACE


